import axios from 'axios'
import md5 from 'md5'
import { cookie } from './storage'


// 客服端APPKEY
const appKey = 's4Zqj8RDVVjyXFPmOslIkCd88x3Yimha';

console.log(`${import.meta.env.VITE_APP_URL}`)

var instance = axios.create({
  baseURL: `${import.meta.env.VITE_APP_URL}`, //接口统一域名
  timeout: 6000, //设置超时
  // withCredentials: true,
  headers: {
      'Content-Type': 'application/json;',
  }
})

let cancel = {}
let promiseArr:any = []
const CancelToken = axios.CancelToken

// 签名数据排序
const signString = function (data:any) {
  var obj = { ...data };
  var arr = new Array();
  var num = 0;
  for (var i in obj) {
    arr[num] = i;
    num++;
  }
  var sortArr = arr.sort();
  var stringA = '';
  var j = 0;
  for (var h in sortArr) {
    stringA += sortArr[h] + '=' + obj[sortArr[h]];
    if (j < sortArr.length - 1) {
      stringA += '&';
    }
    j++;
  }
  return stringA;
}

// http request 拦截器
instance.interceptors.request.use(
  config => {
    // 发起请求时，取消掉当前正在进行的相同请求
    let url = config.url || ''
    let hasCancel = false
    promiseArr.forEach((item:any) => {
      if (item.url === url) {
        item.cancel('操作取消')
        item.cancel = cancel
        hasCancel = true
      }
    })

    if (!hasCancel) {
      promiseArr.push({
        url, cancel
      })
    }

    if (config.method === 'POST') {
      config.data = JSON.stringify(config.data);
    }

    let token = cookie.get('token') || ''

    let headers = {
      ...config.headers
    };
 
    if (token) {
      headers['Authori-zation'] = 'Bearer ' + token
    }

    config.headers = headers

    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// http response 拦截器
instance.interceptors.response.use(
  response => {
    let data = response.data
    return data
  },
  error => {
    if (error) {
      console.log(222,error)
      return '请求失败'
    }
    return Promise.reject(error)
  }
)

// http 请求
const request = (method:string, url:string, param:object) => {
  return new Promise((resolve, reject) => {
    if (!param) {
      param = {}
    }
    let req = {}
    if (method === 'get') {
      req = { params: param || {} }
    } else {
      req = { data: param || {} }
    }
    let data:any = {
      method,
      url,
      ...req,
      cancelToken: new CancelToken(c => {
        cancel = c
      })
    };
    axios(data).then(res => {
      resolve(res)
    }).catch(error => {
      reject(error)
    })
  })
}

export const http = {
  // get请求
  async get(url:string, param:object) {
    return request('get', url, param)
  },
  // post请求
  async post(url:string, param:object) {
    return request('post', url, param)
  },
  // put请求
  async put(url:string, param:object) {
    return request('put', url, param)
  },
  // delete请求
  async delete(url:string, param:object) {
    return request('delete', url, param)
  }
}
